package com.simen.hellobytes.encrypt;

import com.simen.hellobytes.exception.InitAlgorithmException;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.cert.X509Certificate;

/**
 * 解析CERT.RSA文件证书信息
 *
 * @author Created by Simen.
 * @date 创建日期 2018/9/25 11:46
 * @modify 修改者 Simen
 */
public class CERTRSAUtil {

    public static X509Certificate getX509Certificate(String x509CertificateFilePath) throws InitAlgorithmException {
        return getX509Certificates(x509CertificateFilePath)[0];
    }

    public static X509Certificate[] getX509Certificates(String x509CertificateFilePath) throws InitAlgorithmException {
        FileInputStream fis = null;

        try {
            fis = new FileInputStream(x509CertificateFilePath);

            //PKCS7是JDK内部专用 API, 可能会在未来发行版中删除
            Class pkcs7Cls = Class.forName("sun.security.pkcs.PKCS7");

            Constructor<?> constructor = pkcs7Cls.getDeclaredConstructor(InputStream.class);

            if (!constructor.isAccessible()) {
                constructor.setAccessible(true);
            }

            Object pkcs7 = constructor.newInstance(fis);

            Method method = pkcs7Cls.getDeclaredMethod("getCertificates");
            if (!method.isAccessible()) {
                method.setAccessible(true);
            }

            return (X509Certificate[]) method.invoke(pkcs7);
        } catch (ClassNotFoundException e) {
            throw new InitAlgorithmException(e);
        } catch (NoSuchMethodException e) {
            throw new InitAlgorithmException(e);
        } catch (IllegalAccessException e) {
            throw new InitAlgorithmException(e);
        } catch (InstantiationException e) {
            throw new InitAlgorithmException(e);
        } catch (InvocationTargetException e) {
            throw new InitAlgorithmException(e);
        } catch (FileNotFoundException e) {
            throw new InitAlgorithmException(e);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                }
            }
        }
    }

}
